import constantRouterMap from '@/router/constantRoutes'
import asyncRouterMap from '@/router/asyncRoutes'

import authority from '@/utils/authority'

function hasMenu(name, menu) {
  const { alias } = menu.meta || {}
  const menus = alias ? [alias, menu.name] : [menu.name]
  return menus.includes(name)
}

function getRouter() {
  const { menu = [], is_admin = false } = authority.get() || {}
  // const { menu = [] } = authority.get() || {}
  // const is_admin = true

  let addRouters = []

  // 过滤有权限的路由
  function permissionMenu(routerMap) {
    return routerMap.filter(item => {
      const hasPermission = menu.find(it => hasMenu(it, item))
      if (hasPermission && item.children && item.children.length) {
        item.children = permissionMenu(item.children)
      }
      return hasPermission
    })
  }

  // 获取当前角色所有权限的路由菜单
  const permissionRouter = () => {
    let routers = []
    if (is_admin) {
      addRouters = asyncRouterMap
      routers = constantRouterMap
      const target = routers.find(it => it.path === '/')
      target.children = [...target.children, ...addRouters]
    } else {
      // addRouters = permissionMenu(JSON.parse(JSON.stringify(asyncRouterMap)))
      addRouters = permissionMenu(asyncRouterMap)
      routers = constantRouterMap
      const target = routers.find(it => it.path === '/')
      target.children = [...target.children, ...addRouters]
    }
    return routers
  }

  const routers = permissionRouter()

  return {
    routers,
    addRouters
  }
}
const { routers, addRouters } = getRouter()

const permission = {
  state: {
    routers,
    addRouters
  },
  mutations: {
    SET_PERMISSION_ROUTER(state) {
      const { routers, addRouters } = getRouter()
      state.routers = routers
      state.addRouters = addRouters
    }
  },
  actions: {}
}

export default permission
